//
//  BIDPropertyWorkConditionDetailViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/10.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDPropertyWorkConditionDetailViewController.h"
#import "BIDPropertyWorkConditionDetailHeaderView.h"
#import "BIDLeaveMessageForPropertyWorkCell.h"
#import "UIView+FindFirstResponder.h"
#import "BIDCustomTextView.h"
#import "NSDate+Category.h"
#import <SDWebImage/UIImageView+WebCache.h>


//物业工作详情
static NSString *propertyWorkConditionDetailURL = @"propertyAndroid/getById.action";
//留言列表
static NSString *leaveMessageListURL = @"propertyMessageAndroid/list.action";
//回复
static NSString *replyURL = @"propertyMessageAndroid/add.action";
//点赞
static NSString *supportURL = @"propertyLikeAndroid/add.action";

@interface BIDPropertyWorkConditionDetailViewController ()<UITableViewDelegate, UITableViewDataSource, BIDPropertyWorkConditionDetailHeaderViewDelegate, UITextViewDelegate>
{
    NSArray *_dataSourceArr;
    BIDPropertyWorkConditionDetailHeaderView *_headerView;
    BIDLeaveMessageForPropertyWorkCell *_tempCell;
    BOOL _bRegister;
}
@end

@implementation BIDPropertyWorkConditionDetailViewController
@synthesize propertyWorkID;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"物业工作";
    _dataSourceArr = [[NSArray alloc] init];
    _tableView.tableFooterView = [[UIView alloc] init];
    _tempCell = [[[NSBundle mainBundle] loadNibNamed:@"BIDLeaveMessageForPropertyWorkCell" owner:self options:nil] lastObject];
    _messageTextView.placeholder = @"留言";
    _messageTextView.clipsToBounds = YES;
    _messageTextView.layer.cornerRadius = 3.f;
    //
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
    [_tableView addGestureRecognizer:tapGR];
    //
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], propertyWorkConditionDetailURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&property.id=%@", [AppDelegate getUserId], self.propertyWorkID];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            CGSize screenSize = [UIScreen mainScreen].bounds.size;
            _headerView = [[[NSBundle mainBundle] loadNibNamed:@"BIDPropertyWorkConditionDetailHeaderView" owner:self options:nil] lastObject];
            _headerView.delegate = self;
            CGRect headerViewFrame = _headerView.frame;
            headerViewFrame.size.width = screenSize.width;
            headerViewFrame.size.height = screenSize.width*255/320;
            _headerView.frame = headerViewFrame;
            _tableView.tableHeaderView = _headerView;
            [_headerView prepareLayoutWithDic:responseDic];
            //
            [self fetchLeaveMessage];
        }
    }];
}

/**
 获取留言列表
 */
- (void)fetchLeaveMessage
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], leaveMessageListURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&searchParam.propertyId=%@", [AppDelegate getUserId], self.propertyWorkID];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            _dataSourceArr = [[NSArray alloc] initWithArray:responseDic[@"rows"]];;
            [_tableView reloadData];
        }
    }];
}

- (void)tapGestureHandler:(UITapGestureRecognizer *)tapGR
{
    [_messageTextView resignFirstResponder];
}

/**
 留言
 */
- (void)toReply
{
    NSString *strMsg = _messageTextView.text;
    if(strMsg.length == 0)
    {
    }
    else
    {
    }
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], replyURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&propertyMessage.propertyId=%@&propertyMessage.message=%@", [AppDelegate getUserId], self.propertyWorkID, strMsg];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            _messageTextView.text = @"";
            [_messageTextView resignFirstResponder];
            [self fetchLeaveMessage];
        }
    }];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.keyboardHeight = keyboardSize.height;
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.25f];
    _bottomForMessageViewConstraint.constant = self.keyboardHeight;
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.30f];
    _bottomForMessageViewConstraint.constant = 0;
    [UIView commitAnimations];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat height = textView.contentSize.height;
    if(height >= 89)
    {
        _heightForMessageViewConstraint.constant = 89;
    }
    else
    {
        _heightForMessageViewConstraint.constant = height+10>40 ? height+10 : 40;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"])
    {
        [self toReply];
        return NO;
    }
    else
    {
        return YES;
    }
}

#pragma mark - BIDPropertyWorkConditionDetailHeaderViewDelegate

/**
 点赞
 */
- (void)toSupport
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], supportURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&propertyLike.propertyId=%@", [AppDelegate getUserId], self.propertyWorkID];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            //点赞数目加1
            [_headerView supportPlus];
        }
    }];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    NSUInteger row = indexPath.row;
    if(!_bRegister)
    {
        _bRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDLeaveMessageForPropertyWorkCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
    }
    BIDLeaveMessageForPropertyWorkCell *msgCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    NSDictionary *dic = _dataSourceArr[row];
    NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], dic[@"photo"]];
    [msgCell.imgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"defaultPortrait.png"]];
    msgCell.contentLabel.text = dic[@"message"];
    //
    NSString *strName = dic[@"nickName"];
    NSDate *date = [BIDGlobalMethods transToNSDateByFormatter:@"yyyy-MM-dd HH:mm:ss" fromStringDate:dic[@"createTime"]];
    NSString *strTime = [date formattedTime];
    NSString *strTitle = [[NSString alloc] initWithFormat:@"%@ %@", strName, strTime];
    NSMutableAttributedString *strAttribute = [[NSMutableAttributedString alloc] initWithString:strTitle];
    [strAttribute addAttribute:NSForegroundColorAttributeName value:RGBACOLOR(31, 47, 101, 1.f) range:NSMakeRange(0, strName.length)];
    [strAttribute addAttribute:NSForegroundColorAttributeName value:RGBACOLOR(130, 130, 130, 1.f) range:NSMakeRange(strName.length+1, strTime.length)];
    [strAttribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.f] range:NSMakeRange(strName.length+1, strTime.length)];
    msgCell.titleLabel.attributedText = strAttribute;
    cell = msgCell;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0;
    NSUInteger row = indexPath.row;
    NSDictionary *dic = _dataSourceArr[row];
    NSString *strContent = dic[@"message"];
    _tempCell.contentLabel.preferredMaxLayoutWidth = CGRectGetWidth(tableView.frame) - 64 - 8;
    _tempCell.contentLabel.text = strContent;
    CGSize size = [_tempCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    height = size.height>70 ? size.height+1 : 70;
    return height;
}

@end
